import { defineEventHandler, readMultipartFormData } from 'h3'
import { join } from 'path'
import { writeFile } from 'fs/promises'
import { existsSync, mkdirSync } from 'fs'
import { nanoid } from 'nanoid'
import { ResponseCode, sendSuccessResponse, sendErrorResponse } from '~/server/utils/response'


export default defineEventHandler(async (event) => {
  // 1. 读取上传的文件
  const files = await readMultipartFormData(event)

  if (!files || files.length === 0) {
    // throw createError({
    //   statusCode: 400,
    //   statusMessage: 'No files uploaded'
    // })
    return sendErrorResponse(event, ResponseCode.BAD_REQUEST, 'No files uploaded')
    return
  }

  // 2. 配置上传目录
  const uploadDir = join(process.cwd(), 'public/uploads')
  if (!existsSync(uploadDir)) {
    mkdirSync(uploadDir, { recursive: true })
  }

  // 3. 处理每个文件
  const uploadedFiles = []

  for (const file of files) {
    // 生成唯一文件名
    const ext = file.filename?.split('.').pop() || 'bin'
    const newFilename = `${nanoid()}.${ext}`
    const filePath = join(uploadDir, newFilename)

    // 写入文件
    await writeFile(filePath, file.data)

    uploadedFiles.push({
      originalName: file.filename,
      fileName: newFilename,
      filePath: `/uploads/${newFilename}`,
      size: file.data.length,
      mimeType: file.type
    })
  }

  // 4. 返回上传结果
  // return {
  //   status: 'success',
  //   message: 'Files uploaded successfully',
  //   data: uploadedFiles
  // }

  return sendSuccessResponse(event, {
    data: uploadedFiles
  }, 'Files uploaded successfully')
})